package com.transcargo.action;

import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.transcargo.db.db;
import com.transcargo.db.dbException;
import com.transcargo.errors.ErrorList;

public class DelPostFreightAction extends AuthAction {
	private String id = "";
	ArrayList<String> list_id = null;

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException, ServletActionException {
		id = request.getParameter("id");
		if (id == null) {
			list_id = new ArrayList<String>();
			list = null;
			try {
				list = dbase.execute("SELECT id FROM posted_transport WHERE (user_id mod 100000000)=" + User_Id);
				if (list != null) {
					iter = list.iterator();
					while (iter.hasNext()) {
						String[] res = iter.next();
						if (request.getParameter("id" + res[0]) != null && request.getParameter("id" + res[0]).equals("on")) list_id.add(res[0]);
					}
				}
			} catch (dbException e) {
				System.out.println("Database exception: " + e.getMessage());
				throw new ServletActionException();
			}
		}
    }
    private void servletValidateValues() throws ServletValidationException {
    	
    }
    private void servletExecuteAction() throws ServletActionException {
        db.PreStatement pre = null;
        try {
        	if (id != null) {
        		int Id = Integer.parseInt(id);
        		dbase.executeUpdate("DELETE FROM posted_transport WHERE id=" + Id + " AND user_id=" + User_Id);
        	} else {
        		Iterator<String> iterator = list_id.iterator();
        		while (iterator.hasNext()) {
        			dbase.executeUpdate("DELETE FROM posted_transport WHERE id=" + iter.next() + " AND user_id=" + User_Id);
        		}
        	}
        } catch (dbException e) {
			System.out.println("Database exception: " + e.getMessage());
			throw new ServletActionException();
		}
    }
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		try {
            servletGetValues(request);
            servletValidateValues();
            servletExecuteAction();
            sendRedirect(response, "posts.jsp");
	    } catch (ServletParametersException e) {
            if (e.getMessage() != null) {
                sendError(response, new Exception(e.getMessage()));
            } else {
                sendRedirect(response, "posts.jsp");
            }
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletActionException e) {
            sendError(response, new Exception("" + ErrorList.ERROR_STR_GENERIC + dbase.getError()));
        }
    }
}
